extends Enemy

var is_flip = false
var is_shell = false
var is_shell_moving = false
var cur_direction:int = 0
var has_hurt = false
@onready var timer = $Timer

func hurt():
	if has_hurt:
		die()
		return
	$AnimatedSprite2D.play("death")
	cur_direction = direction
	direction = 0
	var score_label = SCORE.instantiate()
	score_label.text = "100"
	add_child(score_label)
	is_shell = true
	timer.start()
	has_hurt = true
	pass
	
func die():
	var score_label = SCORE.instantiate()
	score_label.text = "1000"
	add_child(score_label)
	$Area2D/CollisionShape2D.set_deferred("disabled",true)
	$CollisionShape2D.set_deferred("disabled",true)
	velocity.y = dead_speed
	get_tree().create_timer(3.0).timeout.connect(queue_free)
	pass

func set_flip():
	if direction == -1:
		is_flip = false
	elif direction == 1:
		is_flip = true
	$AnimatedSprite2D.flip_h = is_flip

func _on_area_2d_body_entered(body):
	#print(body.get_groups())
	if body.is_in_group("block") or body.is_in_group("pip"):
		direction = -direction
		set_flip()
	if body.is_in_group("player"):
		if body.global_position.y - global_position.y < -8:
			if !is_shell:
				hurt()
			else:
				die()
				body.trample_enemy()
		else:
			if is_shell and !is_shell_moving:
				var x_pos = body.global_position.x - global_position.x
				if x_pos > 0:
					direction = -1
				else:
					direction = 1
				speed *= 2.5
				is_shell_moving = true
				timer.stop()
			else:
				body.hurt()
	if body.is_in_group("enemy"):
		if is_shell and is_shell_moving:
			body.hurt()


func _on_timer_timeout():
	is_shell = false
	is_shell_moving = false
	$AnimatedSprite2D.play("walk")
	$Area2D/CollisionShape2D.set_deferred("disabled",false)
	$CollisionShape2D.set_deferred("disabled",false)
	direction = cur_direction
	set_flip()
	pass # Replace with function body.
